package com.lx.pc.restful.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.lx.pc.domain.vo.user.UserVo;
import com.lx.pc.restful.usercookie.UserCookie;
import com.lx.pc.restful.util.SystemEnums;
import com.lx.pc.service.user.IUserService;
  
public class CommonInterceptor extends HandlerInterceptorAdapter{

	@Resource(name = "userService")
	private IUserService userService;
	
    /*@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object arg2) throws Exception {
    	
    	UserCookie userCookie = new UserCookie();
		UserCookieQo userCookieQo = userCookie.getUserInfoCookie(request);
		if (userCookieQo != null) {
			String loginName = userCookieQo.getUserName();
			String password = userCookieQo.getPassword();
			UserVo userVo = userService.findByUsername(loginName);
			if (userVo != null) {
	        	if (userVo.getPassword().equals(password)) {
	        		String lastLoginTime = String.valueOf(System.currentTimeMillis());
	        		userCookieQo.setLastLoginTime(lastLoginTime);
					userCookie.addUserInfoCookie(request,response, userVo);
	        	}
			}
		} else {
			//response.sendRedirect(request.getContextPath() + "/toLogin.do");
			request.getRequestDispatcher("/toLogin.do").forward(request, response);
			return false;
		}
        return true;
    }*/
	
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
            Object arg2) throws Exception {
		String nameCode = SystemEnums.Project.LVXIA_FRONT_WEB.getCode() + "_USER_ID";
		//判断Cookie是否存在该IP
		UserCookie cookies = new UserCookie();
		String ip = UserCookie.getIpAddr(request);
		Cookie cookie = cookies.getCookieByName(request, nameCode);
		if(cookie!=null){
			String usrpwd=cookie.getValue();
			String[] s1=usrpwd.split("-&&&&",4);
			String ip2=s1[0];
			String name=s1[1];
			String password=s1[2];
			if(ip==ip2||ip.equals(ip2)){
				UserVo user = new UserVo();
				user.setUserName(name);
				UserVo userVo = userService.findByUsername(user);
				if(userVo!=null){
					if (userVo.getPassword().equals(password)) {
						//cookies.addUserInfoCookie(request,response, userVo);
						return true;
					}
				}
			}
	      }else{
	          request.getRequestDispatcher("/toLogin.do").forward(request, response); 
	          return false;
	      }
        return true;
    }
    
}
